#include "logger_time.h"

using namespace vpm::log::detail;
#ifdef WIN32
#include <windows.h>
long LoggerTimeStamp::logger_time() {
	return GetTickCount();
}
#else 
#include <sys/time.h>
long LoggerTimeStamp::logger_time() {
	struct timeval tv;
	gettimeofday(&tv, 0);
	return tv.tv_sec * 1000 + tv.tv_usec / 1000;
}
#endif  //POSIX 



long LoggerTimeStamp::logger_start_time() 
{
	// Close to program execution time
	static const long g_start = LoggerTimeStamp::logger_time();
	return g_start;
}

// Make sure someone calls it so that it gets initialized
static long ignore = LoggerTimeStamp::logger_start_time();

long LoggerTimeStamp::logger_elapsed_time() 
{
	return logger_time_diff(LoggerTimeStamp::logger_time(), logger_start_time());
}

bool LoggerTimeStamp::logger_time_is_between(long later, long middle, long earlier) 
{
	if (earlier <= later) {
		return ((earlier <= middle) && (middle <= later));
	} else {
		return !((later < middle) && (middle < earlier));
	}
}

long LoggerTimeStamp::logger_time_diff(long later, long earlier) 
{
	long LAST = 0xFFFFFFFF;
	long HALF = 0x80000000;
	if (logger_time_is_between(earlier + HALF, later, earlier)) {
		if (earlier <= later) {
			return static_cast<long>(later - earlier);
		} else {
			return static_cast<long>(later + (LAST - earlier) + 1);
		}
	} else {
		if (later <= earlier) {
			return -static_cast<long>(earlier - later);
		} else {
			return -static_cast<long>(earlier + (LAST - later) + 1);
		}
	}
}
